/*
 * hudong.com Inc.
 * Copyright (c) 2000-2004 All Rights Reserved.
 */
package middlegen.plugins.ibatis;

import middlegen.Column;

import middlegen.javax.JavaColumn;
import middlegen.javax.Sql2Java;

import middlegen.plugins.ibatis.config.ColumnConfig;
import middlegen.plugins.ibatis.config.DalConfig;
import middlegen.plugins.ibatis.util.Util;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.Logger;

import org.apache.commons.lang.StringUtils;

/**
 * A column decorator relates a database table column
 * to a java class field.
 */
public class IWalletColumn extends JavaColumn {
    /** logger */
    private static final Logger logger = Logger.getLogger(IWalletColumn.class);

    /**
     * Constructor for IWalletColumnDecorator.
     */
    public IWalletColumn(Column subject) {
        super(subject);
    }

    /**
     * Get the IWalletConfig instance associated with the plugin.
     *
     * @return
     */
    protected DalConfig getConfig() {
        return ((IWalletPlugin) getPlugin()).getConfig();
    }
    
    /**
     * 
     * @return
     * 
     * @see middlegen.Column#getDefaultValue()
     */
    public String getResultMapNullValue() {
    	if (StringUtils.isNotEmpty(getDefaultValue())) {
			return getDefaultValue();
    	} else {
			return Util.getDefaultValue(getJavaType());
    	}
    }
    
    /**
     * 
     * @return
     */
    public boolean isNeedResultMapNullValue() {
    	return Sql2Java.isPrimitive(getJavaType());
    }

    /**
     * Get java type without package name.
     *
     * @return
     */
    public String getSimpleJavaType() {
        return Util.getSimpleJavaType(getJavaType());
    }

    /**
     *
     *
     * @see middlegen.PreferenceAware#init()
     */
    protected void init() {
        super.init();
    }

    public ColumnConfig getColumnConfig() {
        return ((IWalletTable) getTable()).getTableConfig().getColumn(getSqlName());
    }

	/* (non-Javadoc)
	 * @see middlegen.javax.JavaColumn#getVariableName()
	 */
	public String getVariableName() {
		if (StringUtils.equals(super.getVariableName(), "return")) {
			return "returnValue";
		} 

		return super.getVariableName();
	}
    /**
     *
     *
     * @see middlegen.javax.JavaColumn#setJavaType()
     */
    public void setJavaType() {
        super.setJavaType();

        String              temp = null;

        ColumnConfig columnConfig = getColumnConfig();

        if ((columnConfig != null) && StringUtils.isNotBlank(columnConfig.getJavaType())) {
            temp = columnConfig.getJavaType();
        } else {
            temp = getConfig().getMappedJavaType(super.getJavaType());
        }

        if (StringUtils.isNotBlank(temp)) {
            super.setJavaType(temp);

            if (Character.isUpperCase(Util.getSimpleJavaType(temp).charAt(0))) {
                ((IWalletTable) getTable()).addDoImport(temp);
            }
        }
    }
}
